﻿using System;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using VivendoByte.UploaderWSS.Properties;
using System.Collections.Generic;

namespace VivendoByte.UploaderWSS
{
    public partial class MainForm : Form
    {
        #region Private Fields
        private ConnectorWSS wss;
        private int lastUploadedFileId;
        private string localFullFilename;
        private string remoteFullFilename;
        private string remoteFilename;
        private string documentLibraryName;
        private string folders;
        private Settings settings; 
        #endregion

        #region ctor
        public MainForm(FileInfo fileToUpload)
        {
            InitializeComponent();

            settings = new Settings();

            sharepointUrl.Url = settings.ServerWS;
            usernameTextBox.Text = settings.Username;
            passwordTextBox.Text = settings.Password;
            domainTextBox.Text = settings.Domain;

            if (fileToUpload != null)
            {
                localFileTextBox.Text = fileToUpload.FullName;
                remoteFileTextBox.Text = fileToUpload.Name;
            }
        }
        #endregion

        #region Browse a file
        private void browseFileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "All files (*.*)|*.*";
            DialogResult res = dlg.ShowDialog();

            if (res.Equals(DialogResult.OK))
            {
                localFileTextBox.Text = dlg.FileName;
                remoteFileTextBox.Text = new FileInfo(localFileTextBox.Text).Name;
            }

            dlg.Dispose();
        }
        #endregion

        private void uploadButton_Click(object sender, EventArgs e)
        {
            if (!sharepointUrl.IsUrlCorrect())
            {
                MessageBox.Show("Some information about url is missing!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            localFullFilename = localFileTextBox.Text;
            remoteFullFilename = settings.Protocol + sharepointUrl.Url + "/" + remoteFileTextBox.Text;
            remoteFilename = remoteFileTextBox.Text;
            documentLibraryName = sharepointUrl.GetPartialUrl(UrlPartEnum.DocumentLibrary);
            folders = sharepointUrl.GetPartialUrl(UrlPartEnum.Folder);
            uploadButton.Enabled = false;
            closeButton.Enabled = false;

            setupConnector();
            worker.RunWorkerAsync();
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            wss = new ConnectorWSS();
        }

        void setupConnector()
        {
            wss.Server = settings.Protocol + sharepointUrl.GetPartialUrl(UrlPartEnum.Server);
            wss.Username = usernameTextBox.Text;
            wss.Password = passwordTextBox.Text;
            wss.Domain = domainTextBox.Text;
            wss.WebSite = sharepointUrl.GetPartialUrl(UrlPartEnum.Website);
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            worker.ReportProgress(25, "Uploading file...please wait...");
            wss.UploadDocument(localFullFilename, remoteFullFilename);

            worker.ReportProgress(50, "Getting new file ID...please wait...");
            lastUploadedFileId = wss.GetIDFromFilename(documentLibraryName, folders, remoteFilename);

            worker.ReportProgress(75, "Preparing metadata...please wait...");
            Dictionary<string, string> values = new Dictionary<string, string>();
            values.Add("Note", this.notesTextBox.Text);

            worker.ReportProgress(100, "Uploading metadata file...please wait...");
            wss.UpdateDocumentMetadata(documentLibraryName, lastUploadedFileId, values);
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uploadButton.Enabled = true;
            closeButton.Enabled = true;
            progressBar.Value = 0;
            stateLabel.Text = string.Empty;

            string message = string.Format("Upload operation complete!\r\n\r\nFile ID : {0}", lastUploadedFileId);
            MessageBox.Show(message, "WSS", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
            stateLabel.Text = e.UserState.ToString();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            settings.Username = this.usernameTextBox.Text;
            settings.Password = this.passwordTextBox.Text;
            settings.Domain = this.domainTextBox.Text;

            if(sharepointUrl.IsUrlCorrect())
                settings.ServerWS = sharepointUrl.GetPartialUrl(UrlPartEnum.Server);

            settings.Save();
        }
    }
}